/*
 * IBM Corporation.
 * Copyright (c) 2014 All Rights Reserved.
 */

package com.ibm.iisp.data.service;

import java.util.HashMap;
import java.util.List;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

import com.ibm.iisp.data.model.DataTable;
import com.ibm.iisp.data.model.DataTableColumn;

/**
 * 类作用：
 * @author Johnny@cn.ibm.com
 * 使用说明：
 */

public class DataCommonService {
	protected Logger log = LoggerFactory.getLogger(getClass());
	@Inject
	protected EntityManager dao;
	@Transactional(readOnly = true)
	public DataTable getDataTable(String tableCode) {
		DataTable dt = dao.find(DataTable.class, tableCode);
		initDataTable(dt);
		getDefaultColumns(dt);
		return dt;
	}

	/*
	 * @param dt
	 */
	protected void initDataTable(DataTable dt) {
		// log.debug("Colums count:{}", dt.getColumns().size());
		for (DataTableColumn dtc : dt.getColumns()) {
			log.debug("Colums options count:{}", dtc.getOptions().size());
		}
	}

	/**
	 * @param dt
	 */
	private void getDefaultColumns(DataTable dt) {
		HashMap<String, DataTableColumn> dtColMap = new HashMap<>();
		for (DataTableColumn dtc : dt.getColumns()) {
			dtColMap.put(dtc.getCode(), dtc);
		}
		Query colQuery = dao.createNamedQuery(DataTable.DATA_TABLE_DEF).setParameter(1, dt.getCode());
		List<?> resultList = colQuery.getResultList();
		for (Object obj : resultList) {
			Object[] cs = (Object[]) obj;
			String colName = (String) cs[0];
			if (!dtColMap.containsKey(colName)) {
				DataTableColumn col = new DataTableColumn();
				col.setCode(colName);
				String name = (String) cs[1];
				// 如果有“：”分隔，就取“：”之前的部分作为中文字段名称
				if (name != null) {
					String[] ns = name.split(":|：|;|；");
					name = ns[0];
				}
				col.setName(name);
				dt.getColumns().add(col);
			}
		}
	}

}
